//导入axios  npm install axios
import axios from 'axios';
import { ElMessage } from 'element-plus'
const baseURL = '/api';
const instance = axios.create({baseURL})
import {useTokenStore} from "@/stores/token";
instance.interceptors.request.use(
    (config)=>{
        const tokenStore=useTokenStore()
        if(tokenStore.token){
            config.headers.Authorization=tokenStore.token
        }
        return config
    },
    (error)=>{
        return Promise.reject(error)
    }
)

import router from '@/router'
//添加响应拦截器
instance.interceptors.response.use(
    result=>{
        if(result.data.code===0){
            return result.data;
        }
        ElMessage({
            message: result.data.message?result.data.message:'服务异常',
            type:'error'
        })
        return Promise.reject(result.data)
    },
    err=>{
        if(err.response.status===401){
            ElMessage({
                message: '请先登录',
                type:'error'
            })
            router.push('/')
        }else{
            ElMessage({
                message: '服务异常',
                type:'error'
            })
        }
        return Promise.reject(err);
    }
)

export default instance;